package com.wan.fragment


import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

import com.wan.R
import com.wan.adapter.ProjectVpAdapter
import com.wan.base.BaseBean
import com.wan.entity.ProjectBean
import com.wan.uitls.APIServices
import com.wan.uitls.CommonUtils
import kotlinx.android.synthetic.main.fragment_project.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 *
 * 一个tab 和一个 Viewpager
 * 一个动态的tab 和一个动态的viewPager
 *
 */
class ProjectFragment : Fragment() {

    private lateinit var tabCall: Call<BaseBean<ArrayList<ProjectBean>>>

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_project, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        var fragments: ArrayList<Fragment> = ArrayList()
        var titles: ArrayList<String> = ArrayList()
        var projectVpAdapter = ProjectVpAdapter(childFragmentManager, fragments, titles)
        project_content_vp.adapter = projectVpAdapter

        project_title_tb.setupWithViewPager(project_content_vp)

        var retrofit = Retrofit.Builder()
                .baseUrl(APIServices.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        var apiServices = retrofit.create(APIServices::class.java)
        tabCall = apiServices.getProjectList()
        tabCall.enqueue(object : Callback<BaseBean<ArrayList<ProjectBean>>> {
            override fun onFailure(call: Call<BaseBean<ArrayList<ProjectBean>>>, t: Throwable) {
                CommonUtils.toastWord(context!!, "访问失败")
            }

            override fun onResponse(call: Call<BaseBean<ArrayList<ProjectBean>>>, response: Response<BaseBean<ArrayList<ProjectBean>>>) {
                CommonUtils.toastWord(context!!, "访问成功")
                var dataList = response.body()!!.data
                for (i in 0 until dataList.size) {
                    var projectBean = dataList[i]
                    titles.add(projectBean.name)
                    var bundle = Bundle()
                    bundle.putInt(ProjectItemFragment.CID, projectBean.id)
                    fragments.add(ProjectItemFragment.newInstance(bundle))
                }
                projectVpAdapter.notifyDataSetChanged()
                project_content_vp.offscreenPageLimit = fragments.size - 1
            }
        })
    }

    override fun onDestroy() {
        if (tabCall != null && tabCall.isExecuted) {
            tabCall.cancel()
        }
        super.onDestroy()
    }
}
